package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ArticleCollectionBehaviorService;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author lzq
 * @data 2023/5/11 12:47
 */
@Service
public class ArticleCollectionBehaviorServiceImpl implements ArticleCollectionBehaviorService {

    //收藏
    public static final String COLLECTION_BEHAVIOR ="collection.behavior";
    @Autowired
    private CacheService  cacheService;
    /**
     * 文章收藏
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collectionBehavior(CollectionBehaviorDto dto) {
        //参数校验
        if (dto.getEntryId()==null||dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //判断缓存中是否已经收藏
        String jsonDtoStr = (String) cacheService.hGet(COLLECTION_BEHAVIOR + user.getId().toString(), dto.getEntryId().toString());
        CollectionBehaviorDto jsonDto = JSON.parseObject(jsonDtoStr, CollectionBehaviorDto.class);
        if (StringUtils.isNotBlank(jsonDtoStr)&&dto.getOperation()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"已收藏");
        }
        if (dto.getOperation()==0){
            //收藏
            cacheService.hPut(COLLECTION_BEHAVIOR + user.getId().toString(), dto.getEntryId().toString(),JSON.toJSONString(dto));
        }else {
            //不收藏,删除缓存
            cacheService.hDelete(COLLECTION_BEHAVIOR + user.getId().toString(),  dto.getEntryId().toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
